package com.hmdp.utils;

import org.apache.tomcat.jni.Local;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
//全局唯一id生成工具
public class RedisIdWorker {
    private static final long BEGIN_TIMESTAMP = 1640995200L;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    private int LEFT_COUNT_BITS = 32;

    /**
     * 生成全局唯一ID
     * @param keyPrefix
     * @return
     */
    public long nextId(String keyPrefix){
         //1.生成时间戳
         LocalDateTime localDateTime = LocalDateTime.now();
         long nowSecond = localDateTime.toEpochSecond(ZoneOffset.UTC);
         long timestamp = nowSecond - BEGIN_TIMESTAMP;
         //2.生成序列号
         //2.1 获取当前日期，精确到天
         String date = localDateTime.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
         //key的拼接用来区分不同的业务，同时又可以防止一达到上限2^64。
         long count = stringRedisTemplate.opsForValue().increment("icr:"+keyPrefix+date);
         //3.拼接返回
         return timestamp << LEFT_COUNT_BITS | count;
     }


    public static void main(String[] args) {
        LocalDateTime time = LocalDateTime.of(2022,1,1,0,0,0);
        long seconds = time.toEpochSecond(ZoneOffset.UTC);
        System.out.println(seconds);
    }
}
